package me.jzn.alib.drawable;

import android.content.ContentResolver;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;

import androidx.annotation.IdRes;
import androidx.annotation.RequiresApi;
import androidx.core.graphics.drawable.IconCompat;

import me.jzn.alib.ALib;
import me.jzn.core.Core;

@RequiresApi(api = Build.VERSION_CODES.M)
public class IconDrawableType implements DrawableType {
    private Icon icon;

    public IconDrawableType(Icon icon) {
        this.icon = icon;
        if (Core.isDebug()) {
            //把File作为IconDrawable的时候，getDrawable()会报资源泄露。
            //java.lang.Throwable: Explicit termination method 'close' not called
            //因此，如果时这种情况，就要自己把file转换成Drawable
            IconCompat icp = IconCompat.createFromIcon(ALib.app(), icon);
            if (icp.getType() == Icon.TYPE_URI) {
                Uri uri = icp.getUri();
                if (uri != null && _isFileUri(uri)) {
                    //如果是file，需要解决资源泄露的问题.
                    throw new IllegalArgumentException("请确保Icon的来源不是File,否则会资源泄露!");
//                return Drawable.createFromPath(uri.getPath());
                }
            }
        }
    }

    private static boolean _isFileUri(Uri uri) {
        String scheme = uri.getScheme();
        if (scheme == null && uri.getPath().startsWith("/")) {
            return true;
        }
        return ContentResolver.SCHEME_FILE.equals(uri.getScheme());
    }

    public Icon getIcon() {
        return icon;
    }

    @Override
    public Drawable getDrawable() {
        return icon.loadDrawable(ALib.app());
    }

    @Override
    public void setImageView(ImageView iv) {
        iv.setImageIcon(icon);
    }

    @Override
    public void setBackground(View view) {
        Drawable drawable = icon.loadDrawable(view.getContext());
        view.setBackground(drawable);
    }

    @Override
    public void setRemoteViews(RemoteViews rv, @IdRes int imageViewId) {
        rv.setImageViewIcon(imageViewId, icon);
    }
}
